import React from 'react';
import { connect } from 'dva';
import { Icon, WingBlank, Modal } from 'antd-mobile';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import { Helmet } from 'react-helmet';
import styles from './TrainsMainPage.less';
import styles2 from './ExamPaperListPage.less';
import classnames from 'classnames';

const _ = require('lodash');


const isEqual = (selectKey, answer) => {
  let boo = true;
  const selectArr = selectKey.split(',');
  const answerArr = Array.isArray(answer) ? answer : [answer];

  if (selectArr.length !== answerArr.length) {
    boo = false;
  } else {
    for (const item of selectArr) {
      if (answerArr.indexOf(item) === -1) {
        boo = false;
      }
    }
  }
  return boo;
};

const Result = (props) => {
  if (props.selectKey && props.answer) {
    if (isEqual(props.selectKey, props.answer)) {
      return (<div className={styles.answerRight}><Icon className={styles.icon} type="check-circle-o" size="sm" />答对了
      </div>);
    } else {
      return (
        <div>
          <div className={styles.answerThrong}><Icon className={styles.icon} type="cross-circle" size="sm" />答错了</div>
          <div className={styles.answer}>正确答案是：{props.answer ? props.answer : '?'}</div>
        </div>
      );
    }
  } else {
    return null;
  }
};


class ExamPage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectKey: '',
      startTime: moment().toISOString(),
    };
  }

  componentDidMount() {
    const ref_type = this.props.location.query.ref_type;
    const ref_id = this.props.location.query.ref_id;
    // 查看题目结果，由统计页面跳转过来的
    if (this.props.location.query.checkResult) {
      this.props.fetch({ filter: { ref_type, ref_id }, page: this.props.location.query.checkResult });
      if (!this.props.exam.trains.length) {
        this.props.dispatch({
          type: 'exam/getTrains',
          payload: { ref_type, ref_id },
        });
      }
    } else {
      const startTime = moment().toISOString();
      this.props.fetch({ filter: { ref_type, ref_id } });
      this.props.startExam(startTime, ref_type, ref_id);
    }
  }

  onChange = (selectKey, examItem, page, total, skip) => {
    if (skip || this.props.location.query.checkResult) {
      return;
    }

    if (examItem.type === false) {
      const selectKey2 = this.state.selectKey;
      const arr = selectKey2.split(',').filter(item => item.length);
      const index = arr.indexOf(selectKey);
      if (index !== -1) {
        arr.splice(index, 1);
      } else {
        arr.push(selectKey);
      }
      this.setState({
        selectKey: arr.join(','),
      });
      this.props.doExam(arr.join(','), examItem, this.props.location.query.ref_type, this.props.location.query.ref_id);
    } else {
      this.setState({ selectKey });
      this.props.doExam(selectKey, examItem, this.props.location.query.ref_type, this.props.location.query.ref_id);

      /*setTimeout(() => {
        this.onChangePage(page, total, selectKey);
      }, 500);*/
    }
  };

  onChangePage = (page, total, selectKey) => {
    if (page <= 0) {
      return;
    }
    if (selectKey !== undefined && !this.props.location.query.checkResult) {
      if (!selectKey) {
        return;
      }
    }

    if (page !== total + 1) {
      this.props.fetch({
        filter: {
          ref_type: this.props.location.query.ref_type,
          ref_id: this.props.location.query.ref_id,
        },
        page,
      });
    } else if (this.props.location.query.checkResult) {
      this.props.goBack();
    } else {
      Modal.alert('返回', '练习结束，是否返回，可进行其他练习或者模拟考试？', [
        {
          text: '取消',
          onPress: () => {
          },
        },
        { text: '确定', onPress: this.props.goBack },
      ]);
    }
    this.setState({ selectKey: '' });
  }

  render() {
    const { dispatch, exam } = this.props;
    const item = exam.list[0];
    if (!item) {
      return (
        <div style={{ paddingTop: '0.3rem' }}>
          <div className={styles2.section4} style={{ marginTop: 0 }}>
            <img src={require('../assets/examCircle.png')} alt="" />
          暂无可用的试卷
        </div>
        </div>
      );
    }
    const { current, page, pageSize, total, totalCount, totalPageCount } = exam.pagination;

    let { selectKey } = this.state;
    const arr = [];
    for (const i in item.items) {
      arr.push({ label: i, value: item.items[i] });
    }

    const preSelectKey = _.get(_.find(exam.trains, { _id: item._id }), 'selectKey');
    const answer = _.get(_.find(exam.trains, { _id: item._id }), 'answer');
    if (preSelectKey) {
      selectKey = preSelectKey;
    }

    return (
      <div>
        <Helmet>
          <title>
            {this.props.location.query.checkResult ? '考试详情' : '练习'}
          </title>
        </Helmet>

        {
          this.props.location.query.checkResult ?
            (
              <div className={styles.num}>

                <div className={styles.correct}>
                  <img src={require('../assets/right.png')} alt="" />
                  <span className={styles.label}>正确:</span>
                  <span className={styles.text}>{this.props.correctNum}</span>
                </div>

                <div className={styles.wrong}>
                  <span className={styles.label}>错误:</span>
                  <span className={styles.text}>{this.props.errorNum}</span>
                </div>

              </div>
            ) : (
              <div>&nbsp;</div>
            )
        }


        <WingBlank>
          <div className={styles.title}>
            <img
              src={require(item.type === false ? '../assets/multiSelection.png' : '../assets/singleSelection.png')}
              alt=""
            />
            {item.question}
          </div>

          <div className={styles.container}>
            {
              arr.map(i =>
                (
                  <div
                    className={classnames({
                      [styles.item]: true,
                      [styles.active]: selectKey.indexOf(i.label) !== -1,
                    })}
                    key={i.label}
                    onClick={() => this.onChange(i.label, item, current + 1, total, selectKey)}
                  >
                    <div
                      className={
                        classnames({
                          [styles.label]: true,
                          [styles.active]: selectKey.indexOf(i.label) !== -1,
                          [styles.circle]: item.type !== false,
                        })
                      }
                    >
                      {
                        selectKey.indexOf(i.label) !== -1 ? '✓' : i.label
                      }
                    </div>
                    <div className={styles.value}>{i.value}</div>
                  </div>
                ))
            }
          </div>

          <Result selectKey={selectKey} answer={answer} />

        </WingBlank>

        <div className={styles.button}>
          <div
            onClick={() => {
              this.onChangePage(current - 1, total);
            }} className={styles.left}
            style={current === 1 ? { visibility: 'hidden' } : {}}
          >
            上一题
          </div>
          <div className={styles.complete}>
            <img src={require('../assets/examReasult.png')} alt="" />
            <span className={styles.current}>{current}</span>
            <span className={styles.total}>/{total}</span>
          </div>
          <div
            onClick={() => {
              this.onChangePage(current + 1, total, selectKey);
            }} className={styles.right}
            style={!selectKey.length ? { visibility: 'hidden' } : {}}
          >
            {current === total ? '结束' : '下一题'}
          </div>
        </div>

      </div>
    );
  }
}

const caculateNum = (exam) => {
  const trains = exam.trains;
  let correct = 0;
  for (let i = 0; i < trains.length; i++) {
    if (isEqual(trains[i].selectKey, trains[i].answer)) {
      correct++;
    }
  }
  return correct;
};

export default connect(
  (state, props) => {
    const ref_type = props.location.query.ref_type; // decodeURIComponent(props.location.query.ref_type);
    const ref_id = props.location.query.ref_id;
    return {
      exam: state.exam,
      ref_type,
      ref_id,
      correctNum: caculateNum(state.exam),
      errorNum: state.exam.trains.length - caculateNum(state.exam),
    };
  },
  (dispatch, props) => {
    return {
      fetch(payload) {
        dispatch({ type: 'exam/fetch', payload: { ...payload } });
      },
      doExam(selectKey, param, ref_type, ref_id, startTime) {
        dispatch({ type: 'exam/doExam', payload: { ...param, selectKey, ref_type, ref_id, type: 'trains', startTime } });
      },
      getTrains(ref_type, ref_id) {
        dispatch({ type: 'exam/getTrains', payload: { ref_type, ref_id, type: 'trains' } });
      },
      startExam(startTime, ref_type, ref_id) {
        dispatch({ type: 'exam/startExam', payload: { startTime, ref_type, ref_id, type: 'trains', trains: '' } });
      },
      goToReasult(time) {
        dispatch(routerRedux.push({
          pathname: '/examReasult',
          query: { time, ref_type: props.location.query.ref_type, ref_id: props.location.query.ref_id },
        }));
      },
      goBack() {
        dispatch(routerRedux.goBack());
      },
    };
  },
)(ExamPage);
